package com.zzz.filer;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.annotation.WebInitParam;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
 * @author zzr
 * @date: 2025/07/25  08:21
 * @description:
 */
@WebFilter(
        filterName = "loggingFilter",
        initParams = {@WebInitParam(name = "dateTimePattern", value = "yyyy-MM-dd HH:mm:ss")},
        urlPatterns = {"/servletA","*.html"},
        servletNames = {"servletBName"}
)
public class LoggingFilter implements Filter {

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
       // 参数父转子
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        /**
         * 1. 请求到达目标资源之前的功能代码
         *     判断是否登录
         *     判断权限是否满足
         * 2. 放行代码
         * 3. 相应之前 HttpServletResponse 转换为响应报文之前的功能代码
         */

        // 请求到达目标资源之前的代码
        String requestURI = request.getRequestURI();
        String time = dateFormat.format(new Date());
        String beforeLogging = requestURI + "在" + time + "被请求了";
        System.out.println(beforeLogging);

        long t1 = System.currentTimeMillis();

        // 放行
        filterChain.doFilter(servletRequest,servletResponse);

        // 响应之前的功能代码
        long t2 = System.currentTimeMillis();
        String afeterLogging = requestURI + "在" + time + "的请求耗时：" + (t2 - t1) + "毫秒";
        System.out.println(afeterLogging);
    }
}
